package com.onemore.task.remote;

import java.sql.SQLException;
import java.util.Date;

import org.voovan.http.server.HttpResponse;
import org.voovan.tools.log.Logger;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.onemore.task.OneJdbc;
import com.onemore.task.model.ModelCangku;
import com.onemore.task.model.ModelJordermx;
import com.onemore.task.model.ModelJsend;
import com.onemore.task.model.ModelKuWei;
import com.onemore.task.model.ModelShangpin;
import com.onemore.task.model.ModelSpgg1;
import com.onemore.task.model.ModelSpgg2;
import com.onemore.task.model.ModelVendor;

public class TaskJsend extends RmtTaskBase{
	String required_field[] = {"DJBH","RQ",
			"QYDM",//结算渠道
			"DM1",//供货商代码*
			"QDDM",//渠道代码
			"DM2",//仓库
			"DM2_1",//库位代码*
			"BYZD1",//价格选定
			"BYZD12",//折扣
			"YGDM"//业务员
			};
	/**
	 * 处理采购通知单报文
	 * @param jsonObject
	 * @param response
	 */
	public void process(JSONObject jsonObject,HttpResponse response)
	{
		JSONObject jsendJson = jsonObject;
		//规格有效性校验
		int ret = 0;
		float sum_je = 0;
		int sum_sl = 0;
		outer:do {
			JSONArray itemmxArray = jsendJson.getJSONArray("ITEM_JSENDMX");
			if(itemmxArray == null) {
				message = "接收到的采购通知单报文，未填写ITEM_JSENDMX项";
				Logger.error(message);
				ret = -100;
				break outer;
			}
			////////////////////////////////////////判断单据编号
			if(!jsendJson.containsKey("DJBH") || jsendJson.getString("DJBH") == "") {
				message = "采购通知单单据编号(DJBH)不能为空";
				Logger.error(message);
				ret = -528;
				break outer;
			}
			try {
				if(ModelJsend.isExist(jsendJson.getString("DJBH"))) {//BYZD6 SCM的明细单号
					message = "采购通知单单据编号(DJBH)已存在,DJBH:"+jsendJson.getString("DJBH");
					Logger.error(message);
					ret = -529;
					break outer;
				}
			} catch (SQLException e) {
				message = e.getMessage();
				Logger.error(message);
				ret = -527;
				break outer;
			}
			String djbh = jsendJson.getString(ModelJsend.jsend_field[0]);
			for(int j=0;j<itemmxArray.size();j++) {
				JSONObject itemObject = itemmxArray.getJSONObject(j);
				if(itemObject.containsKey("SL"))
					sum_sl += Integer.valueOf((String)itemObject.getString("SL"));
				if(itemObject.containsKey("JE"))
					sum_je += Float.valueOf((String)itemObject.getString("JE"));
				
				String mxdjbh = itemObject.getString(ModelJordermx.jordermx_field[0]);
				if(!mxdjbh.startsWith(djbh)) {
					message = "规格商品代码单据编号跟主表商品代码不统一";
					Logger.error(message);
					ret = -500;
					break outer;
				}
				if(!itemObject.containsKey("BYZD6") || itemObject.getString("BYZD6") == "") {
					message = "明细表单编号(BYZD6)不能为空";
					Logger.error(message);
					ret = -521;
					break outer;
		    	} 

				if(isFieldEmpty(itemObject.getString("SPDM"))) {
					message = "从SCM接收到的通知明细表中，商品代码为空";
					Logger.error(message);
					ret = -531;
					break outer;
		    	} else
					try {
						if(!ModelShangpin.isValid(itemObject.getString("SPDM"))) {
							message = "SCM与ERP商品代码未同步,在ERP数据库找不到对应的商品代码或该商品未启用";
							Logger.error(message);
							ret = -533;
							break outer;
						}
					} catch (SQLException e1) {
						// TODO Auto-generated catch block
						Logger.error(message);
						ret = -532;
						break outer;
					} 
		    		try {
						setDefault(itemObject,"CKJ",ModelShangpin.getBZJJ(itemObject.getString("SPDM")));
					} catch (SQLException e1) {
						// TODO Auto-generated catch block
						message = e1.getMessage();
						Logger.error(message);
						ret = -532;
						break outer;
					}
		    	try {
					if(OneJdbc.search("JSENDMX", "BYZD6='"+itemObject.getString("BYZD6")+"'")) {//BYZD6 SCM的明细单号
						message = "采购通知单明细表单据编号已存在";
						Logger.error(message);
						ret = -522;
						break outer;
					}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					message = e.getMessage();
					Logger.error(message);
					ret = -523;
					break outer;
				}
			}
			/*if(jsendJson.containsKey("SL")) {
				if(sum_sl != Integer.valueOf(jsendJson.getString("SL"))) {
					message = "主表数量跟次表数量不一致";
					ret = -537;
					Logger.error(message);
					break outer;
				}
			}*/
	    	setDefault(jsendJson,"DM1","000");//供货商代码 参照GongHuoShang表的GHSDM（成品供货商，成品/物料供货商）
	    	setDefault(jsendJson,"QDDM","000");//渠道代码
	    	setDefault(jsendJson,"DM4","002");//入库类型
	    	setDefault(jsendJson,"DM2","000");//仓库代码  参照CANGKU表CKDM
	    	setDefault(jsendJson,"DM2_1","000");//库位代码 参照KUWEI表KWDM/且符合CKKW表
	    	setDefault(jsendJson,"QYDM","000");//结算渠道代码 ？？？
	    	setDefault(jsendJson,"YGDM","000");//业务员
	    	setDefault(jsendJson,"BYZD12","1");//折扣
	    	setDefault(jsendJson,"BYZD1","0");//价格选定
	    	setDefault(jsendJson,"BYZD2","0");//单据状态 未锁定
	    	setDefault(jsendJson,"LLR","0");//打印
	    	setDefault(jsendJson,"SP","0");
	    	setDefault(jsendJson,"JS","0");
	    	setDefault(jsendJson,"YS","1");//审核1
	    	setDefault(jsendJson,"YSRQ",df.format(new Date()));//审核1日期
	    	setDefault(jsendJson,"JZ","1");//审核2
	    	setDefault(jsendJson,"JZRQ",df.format(new Date()));//审核2日期
	    	setDefault(jsendJson,"XC","0");
	    	setDefault(jsendJson,"TJ","0");
	    	setDefault(jsendJson,"ZDR","简派SCM");
	    	try {
		    	checkOutRequired(jsendJson,required_field);
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				message = e.getMessage();
				ret = -532;
				Logger.error(e);
				break outer;
			}
	    	
	    	try {
				ModelVendor.checkVendorValid(jsendJson.getString("DM1"));
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				message = e1.getMessage();
				ret = -533;
				Logger.error(e1);
				break outer;
			}
	    	try {
				ModelCangku.checkValid(jsendJson.getString("DM2"));
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				message = e1.getMessage();
				ret = -534;
				Logger.error(e1);
				break outer;
			}
	    	try {
				ModelKuWei.checkValid(jsendJson.getString("DM2_1"));
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				message = e1.getMessage();
				ret = -535;
				Logger.error(e1);
				break outer;
			}
			for(int i=1;i<11;i++) {
				try {
					if(OneJdbc.insert_jsend(jsendJson) ) {
						break;
					}else {
						message = "插入采购通知失败,可能是明细单号错误,错误计数："+i;
						Logger.error(message);
						if(i == 1) {
							ret = -104;
							break;	    								
						}
					}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					message = e.getMessage();
					ret = -217;
					Logger.error(e);
					break outer;
				}
			}
			for(int j=0;j<itemmxArray.size();j++) {
				JSONObject jsendmx = itemmxArray.getJSONObject(j);
    			for(int i=1;i<11;i++) {
    				try {
						if(OneJdbc.insert_jsendmx(jsendmx)) {
							break;
						}else {
							message = "插入采购通知明细表失败,错误计数："+i;
							Logger.error(message);
							if(i == 1) {
								ret = -105;
								break;	    								
							}
						}
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						message = e.getMessage();
						ret = -217;
						Logger.error(e);
						break outer;
					}
    			}
			}
		}while(false);

		if(ret == 0 || ret == 200) {
			Logger.info("成功插入从SCM获取采购通知单的数据，ret:"+ret+" message:"+message);
		}
		putResult(response, ret,message);
	}
}
